<script setup lang="ts">
import { ref, getCurrentInstance, computed } from 'vue'
import { v4 as UUID } from 'uuid'
import { TableColumnData } from '@arco-design/web-vue'

interface IConfig {
  id?: string
  name?: string
  memo?: string
  urls?: string
  tag?: string
  headless?: boolean
  [key: string]: unknown
}
const tableData = ref<IConfig[]>(getCachedData())

const chromePath = ref(localStorage.getItem('chromePath') || '')
const filter = ref({
  kw: ''
})

const realFilter = ref({
  kw: ''
})
const showTableData = computed(() => {
  const kw = realFilter.value.kw
  if (!kw) {
    return tableData.value
  }
  return tableData.value.filter((item) => {
    return item.name?.includes(kw) || item.memo?.includes(kw)
  })
})

const context = getCurrentInstance()?.appContext.config.globalProperties

window.api.onSelectChromePath((val: string) => {
  chromePath.value = val
  localStorage.setItem('chromePath', val)
})
window.api.onOpenChromeSuccess((id) => {
  context?.$message.success('打开成功')
  const foundData = tableData.value.find((item) => item.id === id)
  if (foundData) {
    foundData.opened = true
  }
})

window.api.onCloseChrome((id) => {
  context?.$message.success('关闭成功')
  const foundData = tableData.value.find((item) => item.id === id)
  if (foundData) {
    foundData.opened = false
  }
})

function getCachedData() {
  const list = localStorage.getItem('chrome-multi-config-list')
  try {
    const res = list ? JSON.parse(list) : []
    return res.map((item) => {
      item.opened = false
      return item
    })
  } catch (error) {
    //
  }
  return []
}

const columns: TableColumnData[] = [
  {
    title: '名字',
    width: 180,
    dataIndex: 'name'
  },
  {
    title: '状态',
    dataIndex: 'opened',
    slotName: 'opened'
  },
  {
    title: '省内存模式',
    width: 120,
    dataIndex: 'headless',
    slotName: 'headless'
  },
  {
    title: '预设网址',
    dataIndex: 'urls',
    width: 300,
    slotName: 'urls'
  },
  {
    title: '备注',
    width: 300,
    dataIndex: 'memo',
    slotName: 'memo'
  },
  {
    title: '操作',
    width: 180,
    dataIndex: 'operation',
    slotName: 'operation',
    fixed: 'right'
  }
]
const currentData = ref<IConfig>({})
const showEditModal = ref(false)

function changeChromePath() {
  window.electron.ipcRenderer.send('selectChromePath')
}

function openChrome(record: IConfig) {
  if (!chromePath.value) {
    context?.$message.error('请先设置谷歌浏览器地址')
    return
  }
  const { id } = record
  if (!id) {
    return
  }
  const params = { ...record, _chromePath: chromePath.value }
  window.electron.ipcRenderer.send('openChrome', params)
}

function closeChrome(record: IConfig) {
  window.electron.ipcRenderer.send('closeChrome', record.id)
}

function handleAdd() {
  if (!chromePath.value) {
    context?.$message.error('请先设置谷歌浏览器地址')
    return
  }
  currentData.value = {
    id: UUID()
  }
  showEditModal.value = true
}

function handleEdit(record: IConfig) {
  showEditModal.value = true
  currentData.value = { ...record }
}

function handleCopy(record: IConfig) {
  currentData.value = { ...record, id: UUID() }
  showEditModal.value = true
}

async function onBeforeOk() {
  const list = tableData.value
  const foundIndex = list.findIndex((item) => item.id === currentData.value.id)
  if (foundIndex > -1) {
    list[foundIndex] = currentData.value
  } else {
    list.push(currentData.value)
  }

  tableData.value = [...list]
  showEditModal.value = false
  saveData(list)
}
function saveData(list) {
  localStorage.setItem('chrome-multi-config-list', JSON.stringify(list))
}
function downloadChrome() {
  window.electron.ipcRenderer.send('openExternalLink', 'https://www.google.cn/intl/zh-CN/chrome/')
}
function search() {
  realFilter.value = { ...filter.value }
}

// function exportConfig() {
//   window.electron.ipcRenderer.send('exportConfig', JSON.parse(JSON.stringify(tableData.value)))
// }
// function importConfig() {
//   window.electron.ipcRenderer.send('importConfig')
// }

function hello() {
  context?.$message.success('开发中，尽请期待 :)')
}
</script>

<template>
  <div class="p-8">
    <div class="text-center text-[30px]">谷歌浏览器多开</div>
    <a-alert>
      该软件依赖谷歌浏览器来运行，如果您的电脑没有安装，请<a-link @click="downloadChrome"
        >点击此处</a-link
      >去下载
    </a-alert>
    <div class="flex items-center mt-8">
      <div class="w-[120px]">谷歌浏览器地址：</div>
      <a-input v-model="chromePath" placeholder="点击修改->" disabled class="flex-1" />
      <a-button type="primary" class="ml-4" @click="changeChromePath">修改</a-button>
    </div>
    <a-divider />
    <div class="flex justify-between">
      <div class="flex items-center">
        <a-input
          v-model="filter.kw"
          placeholder="请输入名字/备注"
          class="w-[200px] ml-4"
          @press-enter="search"
        />
        <a-button type="primary" class="ml-4" @click="search">查找</a-button>
      </div>
      <div>
        <a-button type="primary" class="ml-auto" @click="handleAdd">添加多开配置</a-button>
        <a-button class="ml-4" @click="hello">导出配置</a-button>
        <a-button class="ml-4" @click="hello">导入配置</a-button>
      </div>
    </div>
    <a-table :columns="columns" :data="showTableData" class="mt-4" :pagination="{ pageSize: 100 }">
      <template #urls="{ record }">
        <div v-for="(url, i) in record.urls?.split('\n')" :key="i">{{ url }}</div>
      </template>
      <template #opened="{ record }">
        <a-tag v-if="record.opened" color="green">运行中</a-tag>
        <a-tag v-else color="gray">未运行</a-tag>
      </template>
      <template #headless="{ record }">
        <a-tag v-if="record.headless" color="green">是</a-tag>
        <a-tag v-else color="red">否</a-tag>
      </template>
      <template #memo="{ record }">
        <div v-for="(str, i) in record.memo?.split('\n')" :key="i">{{ str }}</div>
      </template>
      <template #operation="{ record }">
        <a-link v-if="!record.opened" @click="() => openChrome(record)">打开</a-link>
        <a-link v-else status="danger" @click="() => closeChrome(record)">关闭</a-link>
        <a-link @click="() => handleCopy(record)">复制</a-link>
        <a-link @click="() => handleEdit(record)">编辑</a-link>
      </template>
    </a-table>

    <!-- 编辑弹窗 -->
    <a-modal
      v-model:visible="showEditModal"
      title="编辑/新增"
      draggable
      :destroy-on-close="true"
      :on-before-ok="onBeforeOk"
    >
      <a-form ref="formRef" :model="currentData" auto-label-width>
        <a-form-item label="ID" field="id">
          <a-input v-model="currentData.id" disabled />
        </a-form-item>
        <a-form-item label="名字" field="name">
          <a-input v-model="currentData.name" placeholder="请输入名字" />
        </a-form-item>
        <a-form-item
          label="省内存模式"
          field="headless"
          extra="(测试功能，如果失效请关闭)开启时，浏览器会在后台运行，不展示页面。当需要手动输入网址时，不要打开此配置"
        >
          <a-switch v-model="currentData.headless" />
        </a-form-item>
        <a-form-item label="预设网址" field="url" extra="打开浏览器时会自动打开这些网址，一行一个">
          <a-textarea v-model="currentData.urls" placeholder="请输入网址" />
        </a-form-item>
        <a-form-item label="标签" field="tag" extra="抖音直播间水军填dy_sj">
          <a-input v-model="currentData.tag" placeholder="输入标签，用于标识脚本，不知道可不填。" />
        </a-form-item>
        <a-form-item
          v-if="currentData.tag === 'dy_sj'"
          label="水军话术"
          field="comments"
          extra="水军话术，一行一个"
        >
          <a-textarea v-model="currentData.comments as string" placeholder="请输入水军话术" />
        </a-form-item>
        <a-form-item
          v-if="currentData.tag === 'dy_sj'"
          label="话术发送间隔"
          field="sendInterval"
          extra="每发一条间隔多久（单位秒）"
        >
          <a-input-number v-model="currentData.sendInterval as number" :min="1" placeholder="0" />
        </a-form-item>
        <a-form-item v-if="currentData.tag === 'dy_sj'" label="话术发送完行为" field="sendBehavior">
          <a-radio-group v-model="currentData.sendBehavior as number">
            <a-radio :value="1">不再发送</a-radio>
            <a-radio :value="2">过一段时间再次发送</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="currentData.tag === 'dy_sj' && currentData.sendBehavior === 2"
          label="话术发送完冷却"
          field="allCoolDown"
          extra="所有话术发送完冷却间隔多久再次发送（单位分）"
        >
          <a-input-number v-model="currentData.allCoolDown as number" :min="1" placeholder="0" />
        </a-form-item>
        <a-form-item label="备注" field="memo">
          <a-textarea v-model="currentData.memo" placeholder="请输入备注" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
